<template>
    <div class="upload-page-container">
        <!-- 隐藏的 input 元素，专门用于文件和文件夹选择 -->
        <input type="file" ref="fileInputRef" style="display: none" multiple @change="handleFilesSelected" />
        <input type="file" ref="folderInputRef" style="display: none" webkitdirectory multiple
            @change="handleFolderSelected" />

        <div class="upload-page-content">
            <el-page-header @back="goBack">
                <template #content>
                    <span class="text-large font-600 mr-3">上传文件</span>
                </template>
            </el-page-header>

            <div class="upload-settings-box">
                <!-- 1. 上传到 -->
                <el-form-item label="上传到">
                    <el-radio-group v-model="uploadTargetMode">
                        <el-radio-button value="current">当前目录</el-radio-button>
                        <el-radio-button value="specify">指定目录</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <!-- 2. 路径显示/输入 -->
                <div class="path-display-area">
                    <div v-if="uploadTargetMode === 'current'" class="current-path-display">
                        {{ bucketName }}/{{ currentPathDisplay }}
                    </div>
                    <div v-if="uploadTargetMode === 'specify'" class="specify-path-input">
                        <span class="prefix">{{ bucketName }}/</span>
                        <el-input v-model="specifiedPath" placeholder="请输入目标目录，以 / 结尾" />
                    </div>
                </div>

                <!-- 3. 文件ACL设置 -->
                <el-form-item label="文件 ACL" v-loading="isAclLoading" class="acl-form-item">
                    <div class="acl-options-container">
                        <el-radio-group v-model="selectedAcl">
                            <el-radio value="private">私有</el-radio>
                            <el-radio value="public-read">公共读</el-radio>
                            <el-radio value="public-read-write">公共读写</el-radio>
                        </el-radio-group>

                        <el-text v-if="defaultAcl" type="info" size="small" class="acl-description">
                            当前存储桶权限 (<span class="highlight">{{ aclMap[defaultAcl] }}</span>)
                        </el-text>
                    </div>
                </el-form-item>
            </div>

            <div class="upload-actions">
                <!-- 【修改】两个按钮都改为手动触发 -->
                <el-button type="primary" @click="triggerFileSelect">扫描文件</el-button>
                <el-button type="primary" @click="triggerFolderSelect">扫描文件夹</el-button>
            </div>

            <el-table :data="uploadFileList" style="width: 100%; margin-top: 20px;">
                <el-table-column prop="name" label="名称" show-overflow-tooltip />
                <el-table-column prop="directory" label="文件目录" width="200" show-overflow-tooltip />
                <el-table-column prop="type" label="类型" width="180" />
                <el-table-column prop="size" label="文件大小" width="120">
                    <template #default="scope">{{ formatSize(scope.row.size) }}</template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                        <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="removeFile(scope.row.uid)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="upload-summary">
                文件数：{{ uploadFileList.length }} 总计大小：{{ formatSize(totalSize) }}
            </div>

            <el-collapse v-model="activeCollapse" class="advanced-settings-collapse">
                <el-collapse-item title="高级设置" name="1">
                    <el-form label-position="right" label-width="140px">
                        <el-form-item label="分片大小 (MB)">
                            <el-input-number v-model="currentChunkSize" :min="5" :max="5120" />
                            <el-tooltip class="box-item" effect="dark" content="用于分片上传模式。文件大于此值时将采用分片上传。推荐5MB-5GB。"
                                placement="top">
                                <el-icon class="info-icon">
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </el-form-item>
                        <!-- 未来可以在这里添加自定义元数据等更多高级选项 -->
                    </el-form>
                </el-collapse-item>
            </el-collapse>
        </div>

        <div class="page-footer" :style="footerStyle">
            <el-button type="primary" @click="handleNormalUpload" :disabled="uploadFileList.length === 0">
                上传文件
            </el-button>
            <el-button type="primary" @click="handleMultipartUpload" :disabled="uploadFileList.length === 0">
                分片上传
            </el-button>
            <el-button @click="goBack">取消</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import apiClient from '@/api';
// 现在直接从 @/stores (即 stores 文件夹的 index.js) 导入
import { useTransportStore, useLayoutStore, useSettingsStore } from '@/stores';
// --- Props & Router ---
const props = defineProps({
    bucketName: {
        type: String,
        required: true // 建议为 bucketName 加上 required
    },
    path: {
        type: Array,
        default: () => [] // <-- 【核心修正】
    }
});
const router = useRouter();
const route = useRoute();

// --- State ---
const uploadTargetMode = ref('current'); // 'current' 或 'specify'
const specifiedPath = ref('');     // 用于存储用户输入的指定目录

// --- Refs for hidden inputs and state ---
const fileInputRef = ref(null);
const folderInputRef = ref(null);
const uploadFileList = ref([]);
const isUploading = ref(false);
const transportStore = useTransportStore();
const settingsStore = useSettingsStore();

const isAclLoading = ref(true);    // 控制ACL设置区域的加载状态
const selectedAcl = ref('private'); // 默认值设为最安全的'private'
const defaultAcl = ref(null);      // 用于存储从后端获取的桶的真实ACL
const activeCollapse = ref(''); // 控制高级设置面板的展开/收起

// --- 【新增】分片上传相关的状态 ---
const currentChunkSize = ref(100); // 默认100MB, 稍后会被全局设置覆盖

const footerStyle = computed(() => {
    const leftValue = layoutStore.isSidebarCollapsed ? '0px' : '201px'; // 假设收起时宽度为65px
    console.log('计算出的 left 值是:', leftValue); // 【诊断】
    return {
        left: leftValue,
    };
});

// 用于UI显示的映射
const aclMap = {
    'private': '私有',
    'public-read': '公共读',
    'public-read-write': '公共读写',
};

const layoutStore = useLayoutStore();

// --- Computed Properties ---
const currentPathDisplay = computed(() => {
    // props.path 是从路由来的数组，例如 ['11223344']
    if (props.path && props.path.length > 0) {
        return props.path.join('/') + '/';
    }
    return ''; // 如果在根目录，则显示空
});

// --- Computed Properties ---
const totalSize = computed(() => {
    return uploadFileList.value.reduce((sum, item) => sum + item.raw.size, 0);
});

// --- Helper Functions ---
const formatSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const getStatusTagType = (status) => {
    switch (status) {
        case '上传中': return 'primary';
        case '成功': return 'success';
        case '失败': return 'danger';
        default: return 'info';
    }
};

// --- Core Logic ---

// 1. 触发文件/文件夹选择
const triggerFileSelect = () => fileInputRef.value.click();
const triggerFolderSelect = () => folderInputRef.value.click();
const removeFile = (uid) => {
    uploadFileList.value = uploadFileList.value.filter(f => f.uid !== uid);
};
// 6. 返回上一页
const goBack = () => router.back();

// 2. 处理文件选择结果
const handleFilesSelected = (event) => {
    const files = event.target.files;
    if (!files) return;

    for (const file of files) {
        // 检查文件是否已在队列中
        const isExist = uploadFileList.value.some(item => item.relativePath === file.name);
        if (!isExist) {
            uploadFileList.value.push({
                uid: file.name + Date.now(),
                name: file.name,
                directory: '',
                type: file.type || 'N/A',
                size: file.size,
                raw: file, // 保存原始 File 对象
                relativePath: file.name,
            });
        }
    }
    event.target.value = ''; // 清空以便再次选择
};

// 3. 处理文件夹选择结果
const handleFolderSelected = (event) => {
    const files = event.target.files;
    if (!files) return;

    for (const file of files) {
        const fullPath = file.webkitRelativePath;
        // 检查文件是否已在队列中
        const isExist = uploadFileList.value.some(item => item.relativePath === fullPath);
        if (!isExist) {
            const lastSlashIndex = fullPath.lastIndexOf('/');
            const fileName = fullPath.substring(lastSlashIndex + 1);
            const directoryPath = lastSlashIndex > -1 ? fullPath.substring(0, lastSlashIndex + 1) : '/';

            uploadFileList.value.push({
                uid: fullPath + Date.now(),
                name: fileName,
                directory: directoryPath,
                type: file.type || 'N/A',
                size: file.size,
                raw: file,
                relativePath: fullPath,
            });
        }
    }
    event.target.value = ''; // 清空以便再次选择
};

// 4. 从列表中移除文件


onMounted(async () => {
    try {
        const response = await apiClient.get(`/api/v1/buckets/${props.bucketName}/acl`);
        const bucketAcl = response.data.acl;

        // 智能设置默认值（严格一致）
        selectedAcl.value = bucketAcl;
        defaultAcl.value = bucketAcl;

    } catch (error) {
        console.error("获取存储桶ACL失败，将使用默认的'private'权限:", error);
        selectedAcl.value = 'private'; // 保持安全默认
        defaultAcl.value = 'private';
    } finally {
        isAclLoading.value = false;
    }
    currentChunkSize.value = settingsStore.defaultChunkSize;
});

const getFinalBasePath = () => {
    if (uploadTargetMode.value === 'current') {
        const pathParts = route.params.path || [];
        return pathParts.length > 0 ? pathParts.join('/') + '/' : '';
    } else {
        let userPath = specifiedPath.value.trim().replace(/\\/g, '/');
        if (userPath.startsWith('/')) userPath = userPath.substring(1);
        if (userPath && !userPath.endsWith('/')) userPath += '/';
        return userPath;
    }
};

const handleNormalUpload = () => {
    if (uploadFileList.value.length === 0) return;

    const filesToUpload = [];
    const oversizedFiles = [];
    const FIVE_GB = 5 * 1024 * 1024 * 1024;

    for (const task of uploadFileList.value) {
        if (task.raw.size > FIVE_GB) {
            oversizedFiles.push(task.name);
        } else {
            filesToUpload.push(task);
        }
    }

    if (oversizedFiles.length > 0) {
        ElMessage.error({
            message: `以下文件超过5GB，请使用【分片上传】功能：${oversizedFiles.join(', ')}`,
            duration: 5000
        });
    }

    if (filesToUpload.length > 0) {
        transportStore.addUploadTasks(
            filesToUpload,
            props.bucketName,
            getFinalBasePath(),
            selectedAcl.value,
            'normal' // 明确模式为 'normal'
        );
        ElMessage.success(`${filesToUpload.length}个任务已添加至传输列表`);
        uploadFileList.value = uploadFileList.value.filter(f => oversizedFiles.includes(f.name)); // 从列表中移除已添加的任务
    }
};

// 在 ObjectUploadPage.vue 中

const handleMultipartUpload = () => {
    if (uploadFileList.value.length === 0) {
        ElMessage.warning('请先选择文件');
        return;
    }

    const filesForNewTask = [];
    let revivedCount = 0;

    // 步骤1：遍历所有文件，优先尝试复活旧任务
    for (const file of uploadFileList.value) {
        const wasRevived = transportStore.reviveTaskWithFile(file, props.bucketName, getFinalBasePath());
        if (wasRevived) {
            revivedCount++;
        } else {
            filesForNewTask.push(file);
        }
    }

    // 步骤2：对余下的、未匹配上的文件，进行分片或普通上传的分流
    const tasksForMultipart = [];
    const tasksForNormal = [];
    const chunkSizeInBytes = currentChunkSize.value * 1024 * 1024;

    for (const task of filesForNewTask) {
        if (task.raw.size > chunkSizeInBytes) {
            tasksForMultipart.push(task);
        } else {
            tasksForNormal.push(task);
        }
    }

    // 步骤3：将分流后的新任务添加到传输列表
    if (tasksForMultipart.length > 0) {
        transportStore.addUploadTasks(
            tasksForMultipart,
            props.bucketName,
            getFinalBasePath(),
            selectedAcl.value,
            'multipart'
        );
    }
    if (tasksForNormal.length > 0) {
        transportStore.addUploadTasks(
            tasksForNormal,
            props.bucketName,
            getFinalBasePath(),
            selectedAcl.value,
            'normal'
        );
    }

    // 步骤4：给出统一反馈并清空列表
    const totalNewTasks = tasksForMultipart.length + tasksForNormal.length;
    if (revivedCount > 0 || totalNewTasks > 0) {
        let message = '';
        if (revivedCount > 0) message += `${revivedCount}个任务已恢复，`;
        if (totalNewTasks > 0) message += `${totalNewTasks}个新任务已添加，`;
        message += '详情请查看传输列表。';
        ElMessage.success(message);
    }
    uploadFileList.value = [];
};

</script>

<style scoped>
.upload-page-container {
    padding-bottom: 60px;
    /* 容器本身不需要特殊样式，让它自然填充即可 */
    /* 我们只需要确保内容区有足够的padding-bottom */
}

.upload-settings-box {
    margin-top: 20px;
    padding: 24px;
    background-color: #fafafa;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
}

.upload-settings-box .el-form-item {
    margin-bottom: 18px;
}

.upload-settings-box .el-form-item:last-child {
    margin-bottom: 0;
}

/* 1. 解决垂直对齐问题 */
.acl-form-item {
    /* 使用 flex 布局来控制 label 和内容的对齐 */
    display: flex;
    align-items: center;
    /* 垂直居中 */
}

/* Element Plus 的 form-item label 默认有 padding，我们覆盖它 */
.acl-form-item :deep(.el-form-item__label) {
    padding-bottom: 0;
}

/* 2. 解决水平间距问题 */
.acl-options-container {
    display: flex;
    align-items: center;
    gap: 24px;
    /* 在单选框组和提示文字之间创建间距 */
}

/* 3. 高亮显示权限状态 */
.highlight {
    color: var(--el-color-primary);
    /* 使用 Element Plus 的主题色 */
    font-weight: 500;
}

/* (可选) 微调提示文字样式 */
.acl-description {
    white-space: nowrap;
    /* 防止文字换行 */
}

.upload-summary {
    margin-top: 15px;
    font-size: 14px;
    color: #606266;
}

/* 在 ObjectUploadPage.vue 的 <style scoped> 中 */
.upload-mode-selector {
    margin-top: 20px;
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
}

.path-display-area {
    font-family: 'Courier New', Courier, monospace;
    font-size: 14px;
    color: #606266;
    background-color: #f5f7fa;
    /* 浅灰色背景 */
    padding: 8px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-top: -10px;
    /* 向上微调，更紧凑 */
    margin-bottom: 22px;
    /* 与下一个 el-form-item 的间距 */
}

.specify-path-input {
    display: flex;
    align-items: center;
}

.specify-path-input .prefix {
    margin-right: 5px;
    flex-shrink: 0;
    /* 防止被压缩 */
}



.upload-page-content {
    /* 为固定的页脚留出空间，防止最后的内容被遮挡 */
    padding-bottom: 80px;
    /* 页脚高度(60px) + 一些额外间距(20px) */
    padding: 20px;
    /* 您原来的内边距 */
}

.page-footer {
    /* 1. 【关键】使用 position: fixed 将其固定在视口 */
    position: fixed;
    bottom: 0;
    right: 0;

    /* 2. 【关键】left 的值由 JS 动态提供，并添加平滑动画 */
    transition: left 0.3s ease-in-out;

    /* 3. 【关键】确保 z-index 足够高，让它浮在最上层 */
    z-index: 100;

    /* 4. 保留所有外观样式 */
    display: flex;
    align-items: center;
    height: 60px;
    background-color: #ffffff;
    border-top: 1px solid var(--el-border-color);
    border-left: 1px solid var(--el-border-color);
    padding-left: 240px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.upload-settings-section {
    margin-top: 20px;
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
}

.acl-description {
    display: block;
    margin-top: 5px;
    /* 减小与单选框的间距 */
    padding-left: 0;
    /* 不再需要额外缩进 */
}

.upload-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;
    /* 设置与上方设置框的间距 */
}

.advanced-settings-collapse {
    margin-top: 20px;
}

.advanced-settings-collapse .el-form-item {
    margin-bottom: 0;
    /* 折叠面板里的表单项不需要下边距 */
}

.info-icon {
    margin-left: 8px;
    color: #909399;
    cursor: help;
}
</style>